import moment from 'moment'
import store from '@/store'
import { Message } from 'element-ui'
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  }

  const d = new Date(time)

  return (
    d.getFullYear() +
    '-' +
    (d.getMonth() +
      1) +
    '-' +
    d.getDate() +
    ' ' +
    d.getHours() +
    ':' +
    d.getMinutes() +
    ':' +
    d.getSeconds()
  )
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

export function handledErr(err) {
  return !!((err && !err.success) || (err && err.message))
}

export function yearVisibleChange(val, years, form) {
  if (val) {
    if (years.length !== 0) {
      const thisYear = moment().year()
      const thisYearDic = years.find(
        year => year.name === '' + thisYear
      )
      form.year = (thisYearDic && thisYearDic.value) || ''
      form.projectYear = (thisYearDic && thisYearDic.value) || ''
    }
  }
}

function trimArray(arr) {
  arr.map((item, index) => {
    if (item) {
      if (typeof item === 'string') {
        arr[index] = item.trim()
      } else if (item.constructor === Array) {
        trimArray(item)
      } else if (item.constructor === Object) {
        trimObj(item)
      }
    }
  })
}

function trimObj(obj) {
  for (const key in obj) {
    const item = obj[key]
    if (item) {
      if (typeof item === 'string') {
        obj[key] = item.trim()
      } else if (item.constructor === Array) {
        trimArray(item)
      } else if (item.constructor === Object) {
        trimObj(item)
      }
    }
  }
}
export function trimSpace(obj) {
  if (!obj) return obj
  if (typeof obj === 'string') {
    obj = obj.trim()
  } else if (obj.constructor === Array) {
    trimArray(obj)
  } else if (obj.constructor === Object) {
    trimObj(obj)
  }
  return obj
}

// 自动补0
export function returnFloat(value) {
  var value1 = Math.round(parseFloat(value) * 100) / 100
  var s = value1.toString().split('.')
  if (s.length === 1) {
    value1 = value1.toString() + '.00'
    return value1
  }
  if (s.length > 1) {
    if (s[1].length < 2) {
      value1 = value1.toString() + '0'
    }
    return value1
  }
}
// 显示万元单位
export function showUnit(totalInvestment, totalInvestmentUnit) {
  if (totalInvestment.totalInvestment * 1 >= 10000) {
    const arr = (totalInvestment.totalInvestment / 10000 + '').split('.')
    if (arr.length === 1) {
      totalInvestmentUnit.totalInvestmentUnit = arr[0] + '.00'
    } else if (arr.length === 2) {
      if (arr[1].length <= 1) {
        totalInvestmentUnit.totalInvestmentUnit = arr[0] + '.' + arr[1] + '0'
      } else if (arr[1].length > 1) {
        totalInvestmentUnit.totalInvestmentUnit = arr[0] + '.' + arr[1].slice(0, 2)
      }
    }
  } else {
    totalInvestmentUnit.totalInvestmentUnit = ''
  }
}
// 判断项目计划金额是否符合校验规则
export function validateTotalInvestment(totalInvestment) {
  return (
    typeof (totalInvestment.totalInvestment * 1) === 'number' &&
    !isNaN(totalInvestment.totalInvestment * 1) &&
    totalInvestment.totalInvestment.length <= 16
  )
}

export function getCurrentRoutes() {
  const menuTypeMap = store.state.menuTypeMap
  const keys = Object.keys(menuTypeMap)
  let routesName
  keys.forEach(key => {
    if (menuTypeMap[key] === store.state.menuType) {
      routesName = key
    }
  })
  return store.getters[routesName]
}

export function handleDuplication(origin, list, temp = '', count = 0) {
  if (list.findIndex(item => item.toLocaleLowerCase() === (temp && temp.toLocaleLowerCase() || origin.toLocaleLowerCase())) !== -1) {
    count++
    // temp = origin.replace(/^(.+)(\.)(.*)$/, '$1' + `${count}` + '$2' + '$3')
    temp = origin.replace(/^(.+)(\..*)$/, `$1${count}$2`)
    return handleDuplication(origin, list, temp, count)
  } else {
    // const res = count === 0 && origin || origin.replace(/^(.+)(\.)(.*)$/, '$1' + `${count}` + '$2' + '$3')
    const res = count === 0 && origin || origin.replace(/^(.+)(\..*)$/, `$1${count}$2`)
    temp = null
    count = null
    return res
  }
}

export const dealNumber = (num) => {
  if (num !== 0 && num) {
    num = num + ''
    let decimalsStr = ''
    const splitList = num.split('.')
    splitList[1] && (decimalsStr = '.' + splitList[1])
    // 整数部分
    // 将整数部分拆解为单个数字的数组倒序，然后拼装为新的数组，每3位数字进行一次匹配
    const intStrList = splitList[0].split('').reverse().join('').match(/(\d{1,3})/g)
    // 将匹配后的数组用，拼接，再拆解为单个数字的数组，反转为原先数组形式，拼接为完整数字
    const intStr = intStrList.join(',').split('').reverse().join('')
    return intStr + decimalsStr
  }
  return num
}

/**
 *
 * @param {*在NP.round(value, 2)的基础上补0} value
 */
export function saveTwoPoint(value) {
  var s = value.toString().split('.')
  if (s.length === 1) {
    value = value.toString() + '.00'
    return value
  }
  if (s.length > 1) {
    if (s[1].length < 2) {
      value = value.toString() + '0'
    }
    return value
  }
}

/**
 * 清空form
 */
export function resetForm(ref, vm) {
  vm['$refs'][ref].resetFields()
  vm['updateTime'] && (vm['updateTime'] = [])
}

export function hasBtnPermission(btnCode) {
  return store.getters.btns.includes(btnCode)
}
export function exportFile(exportApi, fileName, params) {
  return exportApi(params)
    .then(res => {
      // console.log('res.type', res.data)
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
    .catch(err => {
      if (!handledErr(err)) {
        // console.log('导出', err)
      }
    })
}
export function validateNum(rule, value, callback, name, validField) {
  (() => {
    const toNum = Number(value)
    if ((toNum || toNum === 0) && toNum >= 0) {
      if (toNum > 10000000000000) {
        callback(new Error(name + '不能超过10000000000000'))
      } else {
        callback()
      }
    } else {
      callback(new Error('请输入大于等于0的数字'))
    }
  })()
}
// 路由跳转前设置参数
export function setParams(to, from, next, routesNames, sessionStorageKey, vm) {
  if (routesNames.includes(to.name)) {
    const value = {
      searchForm: { ...vm.searchForm },
      pageSize: vm.pageSize,
      pageNo: vm.pageNo,
      collapseFlag: vm.$refs.commonSearchForm.getCollapse()
    }
    sessionStorage.setItem(sessionStorageKey, JSON.stringify(value))
  }
  next()
}
export function getParams(to, from, next, routesNames, sessionStorageKey, vm) {
  if (routesNames.includes(from.name)) {
    const value = JSON.parse(sessionStorage.getItem(sessionStorageKey))
    if (value) {
      // vm.searchForm = value.searchForm
      vm.pageSize = value.pageSize
      vm.pageNo = value.pageNo
      vm.$refs.commonSearchForm.setCollapse(value.collapseFlag)
    }
  }
}
// 拷贝属性
export function copyProperties(source, target) {
  if (source && target) {
    for (const key in target) {
      if (source.hasOwnProperty(key)) {
        target[key] = source[key]
      }
    }
  }
}
export function handleChange(file, fileList) {
  if (fileList.length > 1) {
    const compareList = fileList.slice(0, fileList.length - 1)
    file.name = handleDuplication(
      file.name,
      compareList.map(item => item.name || item.oldFileName)
    )
    if (file.name !== file.raw.name) {
      // file.raw = new File([file.raw], file.name, { type: file.raw.type })
      // file.raw.uid = file.uid
      Object.defineProperty(file.raw, 'name', {
        writable: true
      })
      file.raw.name = file.name
      file.raw.renameFlag = true
    }
  }

}

// 不是立即上传的文件上传组件使用
export function handleChange2(file, fileList) {
  if (fileList.length > 1) {
    const compareList = fileList.slice(0, fileList.length - 1)
    file.name = handleDuplication(
      file.name,
      compareList.map(item => item.name || item.oldFileName)
    )
    if (file.name !== file.raw.name) {
      file.raw = new File([file.raw], file.name, { type: file.raw.type })
      file.raw.uid = file.uid
    }
  }
}

export function formatDate(time) {
  return time && moment(time).format('YYYY-MM-DD') || ''
}

export const downloadFile = (url) => {
  const iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  iframe.style.height = 0
  iframe.src = url
  document.body.appendChild(iframe)
  setTimeout(() => {
    iframe.remove()
  }, 5 * 60 * 1000)
}
export const generateUUID = () => {
  var d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    d += performance.now() // use high-precision timer if available
  }
  var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid
}

export const throttle = (fn, delay, atLeast) => {
  let timer = null
  let previous = null
  return function() {
    const now = +new Date()
    if (!previous) previous = now
    if (atLeast && now - previous > atLeast) {
      fn()
      previous = now
      clearTimeout(timer)
    } else {
      clearTimeout(timer)
      timer = setTimeout(function() {
        fn()
        previous = null
      }, delay)
    }
  }
}
export const getDraftRules = (rules) => {
  const newRules = {}
  for (const key in rules) {
    if (rules.hasOwnProperty(key) && key !== 'erpNo' && key !== 'userName') {
      newRules[key] = rules[key].slice(1)
    }
  }
  newRules.erpNo = rules.erpNo
  newRules.userName = rules.userName
  return newRules
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
	let search = params;
	search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
	dateRange = Array.isArray(dateRange) ? dateRange : [];
	if (typeof (propName) === 'undefined') {
		search.params['beginTime'] = dateRange[0];
		search.params['endTime'] = dateRange[1];
	} else {
		search.params['begin' + propName] = dateRange[0];
		search.params['end' + propName] = dateRange[1];
	}
	return search;
}
